﻿namespace UnitFundProfitability
{
	using System;
	using System.Windows;
	using UnitFundProfitability.BusinessLogic;

	/// <summary>
	/// Interaction logic for MarkdownRates.xaml.
	/// </summary>
	public partial class MarkdownRates : Window
	{
		#region Constructors
		/// <summary>
		/// Initializes a new instance of the <see cref="MarkdownRates"/> class.
		/// </summary>
		public MarkdownRates()
		{
			InitializeComponent();
			ExistingUnitFunds.DataContext = Manager.GetUnitFunds();
			RateDate.SelectedDate = DateTime.Today.AddDays(-1);
			AddMarkdownRate.Click += new RoutedEventHandler(AddMarkdownRate_Click);
		}
		#endregion

		#region Methods
		/// <summary>
		/// Handles the Click event of the AddMarkdownRate control.
		/// </summary>
		/// <param name="sender">The source of the event.</param>
		/// <param name="e">The <see cref="System.Windows.RoutedEventArgs"/> instance containing the event data.</param>
		private void AddMarkdownRate_Click(object sender, RoutedEventArgs e)
		{
			UnitFund selectedUnitFund = ExistingUnitFunds.SelectedValue as UnitFund;
			if (selectedUnitFund == null)
			{
				MessageBox.Show("Please, select unit fund.", "Select unit fund");
			}
			else
			{
				decimal rateValue;
				if (!decimal.TryParse(Rate.Text, out rateValue))
				{
					MessageBox.Show("Please, enter a valid number.", "Invalid number");
				}
				else
				{
					if (!RateDate.SelectedDate.HasValue)
					{
						MessageBox.Show("Please, select date.", "Select date");
					}
					else
					{
						MarkdownRate markdownRate = new MarkdownRate();
						markdownRate.Date = RateDate.SelectedDate.Value;
						markdownRate.FundId = selectedUnitFund.FundId;
						markdownRate.MarkdownRateId = Guid.NewGuid();
						markdownRate.Rate = rateValue / 100;
						Manager.SetMarkdownRate(markdownRate);
					}
				}
			}
		}
		#endregion
	}
}